﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using CoreCms.Net.Auth.HttpContextUser;
using CoreCms.Net.Configuration;
using CoreCms.Net.Filter;
using CoreCms.Net.IServices;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using Microsoft.AspNetCore.Authorization;
using CoreCms.Net.Caching.AccressToken;
using CoreCms.Net.Model.WeChatEntites;
using CoreCms.Net.Web.Admin.Infrastructure;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using CoreCms.Net.WeChat.Service.HttpClients;
using CoreCms.Net.WeChat.Service.Enums;
using SKIT.FlurlHttpClient.Wechat.Api;
using Microsoft.IdentityModel.Tokens;

namespace CoreCms.Net.Web.Admin.Controllers.Api.WeChat
{
    /// <summary>
    /// 微信菜单
    ///</summary>
    [Description("微信菜单")]
    [Route("api/[controller]/[action]")]
    [RequiredErrorForAdmin]
    [Authorize]
    public class WeChatMenuController : ControllerBase
    {

        private readonly IWeChatApiHttpClientFactory _weChatApiHttpClientFactory;


        /// <summary>
        /// 构造函数
        /// </summary>
        public WeChatMenuController(IWeChatApiHttpClientFactory weChatApiHttpClientFactory)
        {
            _weChatApiHttpClientFactory = weChatApiHttpClientFactory;
        }


        #region 首页数据============================================================
        // POST: Api/WC_Group/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public AdminUiCallBack GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            return jm;
        }
        #endregion


        /// <summary>
        /// 创建菜单
        /// </summary>
        /// <returns></returns>
        [Description("创建菜单")]
        [HttpPost]
        public async Task<AdminUiCallBack> CreateMenu(MenuFull_ButtonGroupForSkit menu)
        {
            var jm = new AdminUiCallBack();

            if (!menu.button.Any())
            {
                jm.msg = "请不要提交空的菜单数据";
                return jm;
            }

            var skitButtons = new List<CgibinMenuCreateRequest.Types.Button>();

            foreach (var itemParent in menu.button)
            {
                if (string.IsNullOrEmpty(itemParent.name) && string.IsNullOrEmpty(itemParent.name)) continue;

                var bt = new CgibinMenuCreateRequest.Types.Button
                {
                    Type = itemParent.type,
                    Key = itemParent.key,
                    Name = itemParent.name,
                    Url = itemParent.url,
                    MiniProgramAppId = itemParent.appid,
                    MiniProgramPagePath = itemParent.pagepath,
                    MediaId = itemParent.media_id,
                    ArticleId = "",
                    SubButtonList = new List<CgibinMenuCreateRequest.Types.Button>()
                };

                if (!itemParent.sub_button.Any()) continue;

                foreach (var btChild in from itemChild in itemParent.sub_button
                                        where !string.IsNullOrEmpty(itemChild.key) || !string.IsNullOrEmpty(itemChild.name)
                                        select new CgibinMenuCreateRequest.Types.Button
                                        {
                                            Type = itemChild.type,
                                            Key = itemChild.key,
                                            Name = itemChild.name,
                                            Url = itemChild.url,
                                            MiniProgramAppId = itemChild.appid,
                                            MiniProgramPagePath = itemChild.pagepath,
                                            MediaId = itemChild.media_id,
                                            ArticleId = ""
                                        })
                {
                    bt.SubButtonList.Add(btChild);
                }
                skitButtons.Add(bt);
            }

            try
            {
                var client = _weChatApiHttpClientFactory.CreateWeXinClient();
                var accessToken = WeChatCacheAccessTokenHelper.GetWeChatAccessToken();
                var request = new CgibinMenuCreateRequest()
                {
                    AccessToken = accessToken,
                    ButtonList = skitButtons
                };

                var response = await client.ExecuteCgibinMenuCreateAsync(request, HttpContext.RequestAborted);
                if (response.ErrorCode == (int)WeChatReturnCode.ReturnCode.请求成功)
                {
                    jm.code = 0;
                    jm.data = response;
                    jm.otherData = menu;
                    jm.msg = "更新成功";
                    return jm;
                }
                else
                {
                    jm.msg = response.ErrorMessage;
                    jm.otherData = menu;
                    return jm;
                }
            }
            catch (Exception ex)
            {
                jm.msg = $"更新失败：{ex.Message}";
                jm.otherData = menu;
                return jm;
            }
        }

        /// <summary>
        /// 获取菜单
        /// </summary>
        [HttpPost]
        [Description("获取菜单")]
        public async Task<AdminUiCallBack> GetMenu()
        {
            var jm = new AdminUiCallBack();
            try
            {
                var client = _weChatApiHttpClientFactory.CreateWeXinClient();
                var accessToken = WeChatCacheAccessTokenHelper.GetWeChatAccessToken();
                var request = new CgibinMenuGetRequest()
                {
                    AccessToken = accessToken
                };

                var response = await client.ExecuteCgibinMenuGetAsync(request, HttpContext.RequestAborted);
                if (response.ErrorCode == (int)WeChatReturnCode.ReturnCode.请求成功)
                {
                    jm.code = 0;
                    jm.data = response;
                    return jm;
                }
                else
                {
                    jm.msg = response.ErrorMessage;
                    return jm;
                }
            }
            catch (Exception ex)
            {
                jm.msg = "菜单不存在或验证失败！";
                jm.otherData = ex.Message;
                return jm;
            }
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <returns></returns>
        [Description("删除菜单")]
        [HttpPost]
        public async Task<AdminUiCallBack> DeleteMenu()
        {
            var jm = new AdminUiCallBack();
            try
            {
                var client = _weChatApiHttpClientFactory.CreateWeXinClient();
                var accessToken = WeChatCacheAccessTokenHelper.GetWeChatAccessToken();
                var request = new CgibinMenuDeleteRequest()
                {
                    AccessToken = accessToken
                };

                var response = await client.ExecuteCgibinMenuDeleteAsync(request, HttpContext.RequestAborted);
                if (response.ErrorCode == (int)WeChatReturnCode.ReturnCode.请求成功)
                {
                    jm.code = 0;
                    jm.data = response;
                    return jm;
                }
                else
                {
                    jm.msg = response.ErrorMessage;
                    return jm;
                }
            }
            catch (Exception ex)
            {
                jm.msg = "菜单不存在或验证失败！";
                jm.otherData = ex.Message;
                return jm;
            }
        }
    }
}
